package com.ruoyi.project.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.sms.SmsUtil;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysDictDataService;
import com.ruoyi.project.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.domain.AjaxResult;

import java.util.concurrent.TimeUnit;

/**
 * 文件管理
 *
 * @author lidong
 */
@Api(tags = "文件管理")
@RestController()
@RequestMapping("/file")
public class CommonController {

    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
//    @GetMapping("download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response,
                             HttpServletRequest request) {
        try {
            if (!FileUtils.isValidFilename(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName =
                    System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @ApiOperation("文件上传")
    @PostMapping("upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", fileName);
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @ApiOperation("文件下载")
    @GetMapping("download")
    public void resourceDownload(String name, HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
        // 本地资源路径
        String localPath = RuoYiConfig.getProfile();
        // 数据库资源地址
        String downloadPath = localPath + StringUtils.substringAfter(name, Constants.RESOURCE_PREFIX);
        // 下载名称
        String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
        FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }

    /**
     * 生成验证码
     */
    @GetMapping("/sendSms")
    public AjaxResult sendUserSmsCode(String userName, String uid) throws Exception {

        if (StringUtils.isBlank(userName) || StringUtils.isBlank(uid)) {
            throw new CustomException("请求缺少参数！");
        }

        SysUser user = userService.selectUserByUserName(userName);
        if (user == null || !UserStatus.OK.getCode().equals(user.getStatus())) {
            throw new CustomException("用户不存在！");
        }

        if (StringUtils.isBlank(user.getPhonenumber())) {
            throw new CustomException("用户未绑定手机号！");
        }
        // 为了更安全可验证uid，是否系统生成，目前暂不考虑

        // 生成随机字串
        String verifyCode = VerifyCodeUtils.genSmsCode(6);

        String verifyKey = Constants.SMS_CODE_KEY + uid;
        try {
            redisCache.setCacheObject(verifyKey, verifyCode, Constants.SMS_CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

            String message = dictDataService.selectDictLabel("sys_sms", "sms_code");
            String smsResult = SmsUtil.sendSmsCode(verifyCode, message, user.getPhonenumber());
        } catch (Exception e) {
            log.error("发送短信失败", e);
            return AjaxResult.error("发送短信失败");
        }
        return AjaxResult.success("发送短信成功");
    }

    /**
     * 生成验证码
     */
    @GetMapping("/verifySmsCode")
    public AjaxResult verifySmsCode(String userName, String smsCode,String uid) throws Exception {

        if (StringUtils.isBlank(userName)
                || StringUtils.isBlank(uid)
                || StringUtils.isBlank(smsCode)) {
            throw new CustomException("请求缺少参数！");
        }
        SysUser user = userService.selectUserByUserName(userName);
        if (user == null || !UserStatus.OK.getCode().equals(user.getStatus())) {
            throw new CustomException("用户不存在！");
        }
        if (StringUtils.isBlank(user.getPhonenumber())) {
            throw new CustomException("用户未绑定手机号！");
        }
        // 为了更安全可验证uid，是否系统生成，目前暂不考虑

        try {

            String verifyKey = Constants.SMS_CODE_KEY + uid;
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null)
                return AjaxResult.error(MessageUtils.message("user.jcaptcha.expire"));

            if (!smsCode.equalsIgnoreCase(captcha))
                return AjaxResult.error(MessageUtils.message("user.jcaptcha.error"));

            redisCache.setCacheObject( Constants.SMS_CODE_KEY+user.getUserName(),uid);
        } catch (Exception e) {
            log.error("短信验证失败", e);
            return AjaxResult.error("短信验证失败");
        }
        return AjaxResult.success("短信验证成功");
    }

    public static void main(String[] args) {
        System.err.println(VerifyCodeUtils.genSmsCode(6));
        System.err.println("17600299327".replaceAll("(\\d{3})\\d{0,5}(\\w{0,3})","$1****$2"));
    }
}
